class Documents::ReportsController < ApplicationController
  before_filter :authenticate_user!
  before_filter :get_conference
  before_filter :conference_should_be_opened, :except => :show
  before_filter :only_member_access
  before_filter :get_report, :only => [:show, :edit, :update]
  before_filter :moderate_only_their_reports, :only => [:edit, :update]

  def new
    @report = @conference.reports.new
  end

  def show
    @comments = @report.document.comments    # TODO move to base controller?
  end

  def create
    @report = @conference.reports.new(params[:report])
    @report.document.user = current_user

    puts @report.document.inspect

    if @report.save
      flash[:notice] = t('conferences.reports.create.success')
      redirect_to documents_conference_path(@conference) and return
    else
      puts @report.document.inspect
      render :action => :new
    end
  end

  def update
    if @report.update_attributes(params[:report])
      flash[:notice] = t('conferences.reports.update.success')
      redirect_to documents_conference_path(@conference) and return
    else
      render :action => :edit
    end
  end

  protected
    def get_conference
      @conference = Conference.find(params[:conference_id])
    end

    def conference_should_be_opened
      unless @conference && @conference.opened?
        flash[:alert] = t('errors.report.conference_not_opened')
        redirect_to documents_conference_path(@conference) and return
      end
    end

    def only_member_access
      @member = @conference.members.include? current_user
      unless @member
        flash[:alert] = t('conferences.member_access_error')
        redirect_to documents_conferences_path
      end
    end

    def get_report
      @report = @conference.reports.find(params[:id])
    end

    def moderate_only_their_reports
      unless @report.document.user == current_user
        flash[:alert] = t('access.errors.denied')   # TODO more info in message
        redirect_to documents_conference_path(@conference)
      end
    end
end
